package com.cwt_taxi_xa.timer;

import com.cwt_taxi_xa.ActivityACC;
import com.cwt_taxi_xa.MainApplication;
import com.cwt_taxi_xa.constants.MyStatus;
import com.cwt_taxi_xa.constants.SPConstants;
import com.cwt_taxi_xa.db.bll.LocalInfoBiz;
import com.cwt_taxi_xa.model.LocalInfo;
import com.cwt_taxi_xa.protocol.DeviceBiz;
import com.cwt_taxi_xa.protocol.DispatchCenterUsers;
import com.cwt_taxi_xa.protocol.Encoder;
import com.cwt_taxi_xa.protocol.EncoderUtil;
import com.cwt_taxi_xa.protocol.MCUUtil;
import com.cwt_taxi_xa.record.RecorderUploadManager;
import com.cwt_taxi_xa.util.AppLog;
import com.cwt_taxi_xa.util.ByteArrayUtil;
import com.cwt_taxi_xa.util.DateUtil;
import com.cwt_taxi_xa.util.ExceptionUtil;
import com.cwt_taxi_xa.util.SPUtils;
import com.cwt_taxi_xa.util.StringUtil;
import com.cwt_taxi_xa.util.Tools;

import java.util.TimerTask;

/**
 * 心跳发送定时器
 * 请保证车牌和设备终端号不为空
 */
public class TimerHeartBeat extends TimerTask {
	private long theadtime = 0;

	private static final String TAG = "TimerHeartBeat";
	private int count = 1; // 位置
	private long firstcountime = 0; // 位置
	private boolean jiaoshi = false;//校时
	public static int postRecording = 0;
	/**上传录音闲置次数*/
	public static int uploadRecCount = 0;

	/**
	 * 平台发送位置监控
	 */
	public static int times = 0;// 次数
	public static int gap = 10;// 间隔
	//报警发送
	public static boolean baojingfasong = false;

	// 判断两次心跳之间是否有接收平台数据，以此判断平台是否连接
	public static int hasReturn = 5;

	public boolean firstaccoff  = true;
	
	int sendH = 0;
	int sendL = 0;

	public int paramValue0020, paramValue0021;
	public int i_time, i_dis;
	//最后执行时间
	public static long lastReTime = 0;

	@Override
	public void run() {
		try {

			lastReTime = System.currentTimeMillis();
//			AppLog.savelog(""+lastReTime);
			
			sendH--;
			sendL--;
			
			if(theadtime==0){
				theadtime = System.currentTimeMillis();
			}
			
			if(!jiaoshi&&DateUtil.in20Century()){
				jiaoshi = true;
				firstcountime = System.currentTimeMillis()-15000;
			}

			if(firstcountime==0){
				firstcountime = System.currentTimeMillis()-15000;
				jiaoshi = DateUtil.in20Century();
			}else{
				//AppLog.d(TAG,"currentTimeMillis-firstcountime:" + (System.currentTimeMillis()-firstcountime) + " /1000 =" + ((System.currentTimeMillis()-firstcountime)/1000));
				count = (int)((System.currentTimeMillis()-firstcountime)/1000);
			}
			//设备号为空不上平台
			if(StringUtil.isNull(DeviceBiz.getDeviceCode())){
				return;
			}
			//车牌为空不上平台
			if(StringUtil.isNull(DeviceBiz.getCarNumberSingleLetter())){
				return;
			}

			if((++uploadRecCount) == 12){
				RecorderUploadManager.clearInfo();
				uploadRecCount = 0;
			}

			if(RecorderUploadManager.isWork() && ++postRecording == 10){
				postRecording = 0;
				RecorderUploadManager.reProgress();
			}

			try {
				if (count % DeviceBiz.getHeartTime() == 0) {
					if(sendH<1){
//				if (heartCount % 60 == 0) {
					if(MainApplication.topActivity!=null){
							MainApplication.topActivity.setStatus(2, hasReturn<3);
					}
					MyStatus.center = hasReturn<5;
					AppLog.savelog("监测多次连平台问题--hasReturn:"+hasReturn);

					DispatchCenterUsers.witeMsgConnected(Encoder.getHeartbeat());
					DispatchCenterUsers.socketManager.sendHeartbeatMessage();
					hasReturn++;
						sendH = 5;
					}
				}
			} catch (Exception e) {
				AppLog.e(ExceptionUtil.getInfo(e));
				e.printStackTrace();
			}






			if(!baojingfasong){
				//正常位置信息上传
				if (times < 1) {
					if(ActivityACC.accon){
						if(!firstaccoff){
							firstaccoff = true;
						}else{
							/** 判断状态和对应心跳间隔 */
							if (SPUtils.getParamBoolean(SPConstants.SPK_signin,SPConstants.SPV_signin)) {

                                int  accOnReportTime = SPUtils.getParamInteger(SPConstants.PARAMS_ACC_ON_REPORT_TIME, 30);
								//AppLog.d(TAG,"ltj------------------- accOnReportTime :" + accOnReportTime);
                                //最优先ACCON优先
							    if(accOnReportTime != 30){
                                    if (count % accOnReportTime != 0) {
                                        //AppLog.d(TAG,"accOnReportTime: return");
                                        return;
                                    }
                                }
								// 运营状态
                                else if (MyStatus.zhongche) {
									// 重车状态
									if (count % DeviceBiz.getFullCarHeartTime() != 0) {
										return;
									}
								} else {
									// 空车状态
									if (count % DeviceBiz.getEmptyCarHeartTime() != 0) {
										return;
									}
								}
							} else {
								// 停运状态
								if (count % DeviceBiz.getOffLineHeartTime() != 0) {
									return;
								}
							}
						}

					}else{
						if(firstaccoff){
							firstaccoff = false;
						}else{
							// 休眠状态
							if (count % 30  != 0) {
								return;
							}
						}
					}
				} else {
					//00===5===360
					if (count % gap != 0) {
						return;
					}
					times--;
				}
			}else{
				baojingfasong = false;
			}


			byte [] locationbyte = EncoderUtil.getLocationInformationByte();
			//byte[] heartBeatByte = Encoder.getLocationInformation(locationbyte);
			byte[] heartBeatAttachByte = getHeartBeatByte(locationbyte);	//附加协议
			byte[] heartBeatByte = Encoder.getLocationInformation(heartBeatAttachByte);//905协议
			//AppLog.d(TAG,"object:" + this + "times:" + times);
			//AppLog.d(TAG,"locationbyte:" + Tools.parseByte2HexStr(locationbyte));
			//AppLog.d(TAG,"heartBeatAttachByte:" + Tools.parseByte2HexStr(heartBeatAttachByte));
			AppLog.d(TAG,"heartBeatByte:" + Tools.parseByte2HexStr(heartBeatByte));
			AppLog.saveTxt("heartBeatByte:" + Tools.parseByte2HexStr(heartBeatByte));
			if(times < 1){
				//位置心跳
				LocalInfo info = new LocalInfo(LocalInfo.TYPE_GPS);
				//info.setData(Tools.parseByte2HexStr(locationbyte));//
				info.setData(Tools.parseByte2HexStr(heartBeatAttachByte));//
				LocalInfoBiz.getInstance().addInfo(info);//添加到数据库
				//LocalInfoBiz.getInstance().postLocationInfo(heartBeatByte,Tools.parseByte2HexStr(locationbyte));
				LocalInfoBiz.getInstance().postLocationInfo(heartBeatByte,Tools.parseByte2HexStr(heartBeatAttachByte));

			}else{
				//位置跟踪监听
				DispatchCenterUsers.witeMsgConnected(heartBeatByte);
			}
			DispatchCenterUsers.socketManager.sendLocationInfoMessage(heartBeatAttachByte);
		} catch (Exception e) {
			AppLog.e(ExceptionUtil.getInfo(e));
			e.printStackTrace();
		}
	}

	/**
	 * 添加附加信息车辆信息,语音评价
	 * @param locationbyte
	 * @return
	 */
	private byte[] getHeartBeatByte(byte [] locationbyte){
		return ByteArrayUtil.concatAll(locationbyte,MCUUtil.mVehicleInformation.getCanExtraInfo());
	}

}
